package com.sc.adminspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.adminspringboot.pojo.Users;
import com.sc.adminspringboot.service.IUsersService;
import com.sc.adminspringboot.utils.ResponseMsg;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户基础信息表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2025-09-22 09:51:11
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    IUsersService usersService;
    /**
     * 用户列表接口：对邮箱进行脱敏处理
     */
    @RequestMapping("list")
    public ResponseMsg usersList(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "20") int limit,
                                 @RequestParam(required = false) String searchKey,
                                 @RequestParam(required = false) String searchValue,
                                 @RequestParam(required = false) String sortBy,
                                 @RequestParam(required = false) String sortOrder) {
        try {
            IPage<Users> pw = new Page<>(page, limit);
            QueryWrapper<Users> qw = new QueryWrapper<>();

            // 添加搜索条件
            if (searchKey != null && !searchKey.isEmpty() && searchValue != null && !searchValue.isEmpty()) {
                switch (searchKey) {
                    case "userId":
                        // 用户ID精确匹配
                        try {
                            qw.eq("user_id", Long.parseLong(searchValue));
                        } catch (NumberFormatException e) {
                            // 如果不是有效数字，不添加条件
                        }
                        break;
                    case "email":
                        // 邮箱模糊搜索
                        qw.like("email", searchValue);
                        break;
                    case "nickname":
                        // 昵称模糊搜索
                        qw.like("nickname", searchValue);
                        break;
                    default:
                        break;
                }
            }

            // 添加排序条件
            if (sortBy != null && !sortBy.isEmpty()) {
                if ("registerTime".equals(sortBy)) {
                    if ("desc".equals(sortOrder)) {
                        qw.orderByDesc("register_time");
                    } else {
                        qw.orderByAsc("register_time");
                    }
                } else if ("status".equals(sortBy)) {
                    if ("desc".equals(sortOrder)) {
                        qw.orderByDesc("status");
                    } else {
                        qw.orderByAsc("status");
                    }
                } else if ("userId".equals(sortBy)) {
                    if ("desc".equals(sortOrder)) {
                        qw.orderByDesc("user_id");
                    } else {
                        qw.orderByAsc("user_id");
                    }
                }
            } else {
                // 默认按用户ID升序排列
                qw.orderByAsc("user_id");
            }

            IPage<Users> usersPage = usersService.page(pw, qw);

            // 脱敏处理：隐藏邮箱中间3个字符
            usersPage.getRecords().forEach(user -> {
                String emailStr = user.getEmail();
                if (emailStr == null || emailStr.length() < 5) {
                    return; // 邮箱为空或太短，跳过
                }

                // 找到 @ 符号的位置
                int atIndex = emailStr.indexOf('@');
                if (atIndex <= 0 || atIndex >= emailStr.length() - 4) {
                    return; // @ 位置不合法或域名太短
                }

                // 前缀：@ 前面的部分，保留第一个字符，其余用 * 替换
                String prefix = emailStr.substring(0, 1) + "***";

                // 后缀：@ 后面的部分，保留最后4个字符
                String suffix = emailStr.substring(atIndex);
                if (suffix.length() > 4) {
                    suffix = suffix.substring(suffix.length() - 4);
                }

                // 组合脱敏后的邮箱
                user.setEmail(prefix + suffix);
            });

            // 返回结构化数据
            Map<String, Object> result = new HashMap<>();
            result.put("records", usersPage.getRecords());
            result.put("total", usersPage.getTotal());
            result.put("size", usersPage.getSize());
            result.put("current", usersPage.getCurrent());
            result.put("pages", usersPage.getPages());

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", result);
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "查询失败: " + e.getMessage(), null);
        }
    }

    @RequestMapping("removeByNo")
    public ResponseMsg del(Integer userId){
        try {
            boolean result = usersService.removeById(userId);
            if (result) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "删除成功", null);
            } else {
                return ResponseMsg.getInstance(ResponseMsg.NOT_FOUND, "用户不存在", null);
            }
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "删除失败: " + e.getMessage(), null);
        }
    }

    @RequestMapping("removes")
    public ResponseMsg delMany(@RequestBody List<Integer> userIds){
        try {
            if (userIds == null || userIds.isEmpty()) {
                return ResponseMsg.getInstance(ResponseMsg.PARAM_ERROR, "用户ID列表不能为空", null);
            }

            boolean result = usersService.removeByIds(userIds);
            if (result) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "批量删除成功", null);
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "批量删除失败", null);
            }
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "批量删除失败: " + e.getMessage(), null);
        }
    }

    @RequestMapping("up")
    ResponseMsg up(@RequestBody Users users){
        boolean result = usersService.updateById(users);
        if (result) {
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改成功", null);
        } else {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "修改失败", null);
        }
    }
}
